#include "HufArc.h"

int testing (FILE * arc)
{
	unsigned int ChkSum = 0;
	unsigned int ChkSum_orig = 0;
	int rc;
	char * buf = (char *) calloc (256,sizeof(char));
	unsigned long long int num = 0;
	unsigned long long int sizeFileSz = 0;
	unsigned int huff_block_size = 0;
	unsigned int i = 0;
	if (!buf)
		cl_exit (TESTING,MEMORY_ERR,arc,buf);
	fseek (arc,7,SEEK_SET);
	while ((rc = fread (buf,sizeof(char),NAME_LEN,arc)) == NAME_LEN)
	{
		ChkSum = 0;
		ChkSum += Crc32 (buf,NAME_LEN);
		num = strToInt (buf,NAME_LEN);
		if ((rc = fread (buf,sizeof(char),num,arc)) != num)
		{
			free (buf);
			fclose (arc);
			return 1;
		}
		ChkSum += Crc32 (buf,num);
		if ((rc = fread (buf,sizeof (char),SIZE_T_8,arc)) != SIZE_T_8)
		{
			free (buf);
			cl_exit (TESTING,READ_ERR,arc,buf);
		}
		ChkSum += Crc32 (buf,SIZE_T_8);
		if ((rc = fread (buf,sizeof(char),SIZE_T_1,arc)) != SIZE_T_1)
			{
				free (buf);
				fclose (arc);
				return 1;
			}
		ChkSum += Crc32 (buf,SIZE_T_1);
			num = strToInt (buf,SIZE_T_1);
			if (num & LEN_8_B )
			{
				if ((rc = fread (buf,sizeof(char),SIZE_T_8,arc)) != SIZE_T_8)
				{
					fclose (arc);
					free (buf);
					return 1;
				}
				ChkSum += Crc32 (buf,SIZE_T_8);
				i = SIZE_T_8;
				sizeFileSz = strToInt (buf,SIZE_T_8);
			} else {
				if ((rc = fread (buf,sizeof(char),SIZE_T_4,arc)) != SIZE_T_4)
				{
					fclose (arc);
					free (buf);
					return 1;
				}
				i = SIZE_T_4;
				ChkSum += Crc32 (buf,SIZE_T_4);
				sizeFileSz = strToInt (buf,SIZE_T_4);
			}
			
			if (!(num & NO_HUFF))
			{
				if ((rc = fread (buf,sizeof(char),SIZE_T_2,arc)) != SIZE_T_2) //read huff-block size
				{
					fclose (arc);
					free (buf);
					return 1;
				}
				ChkSum += Crc32 (buf,SIZE_T_2);
				huff_block_size = strToInt (buf,SIZE_T_2);
				if ((rc = fread (buf,sizeof(char),i,arc)) != i)
				{
					fclose (arc);
					free (buf);
					return 1;
				}
				ChkSum += Crc32 (buf,i);
				sizeFileSz = strToInt (buf,i);
				copy (arc,NULL,huff_block_size,&ChkSum);
			}
			copy (arc,NULL,sizeFileSz,&ChkSum);
			if ((rc = fread (buf,sizeof(char),SIZE_T_4,arc)) != SIZE_T_4)
			{
				return 1;
			}
			ChkSum_orig = strToInt (buf,SIZE_T_4);
	//		printf ("test %u orig %u\n", ChkSum,ChkSum_orig);
			if (ChkSum_orig != ChkSum) return 1;
	}
	return 0;
}